export default class NetWork {
    pageContext = null;
    networkStatusChange = null;
    networkWeakChange = null;
    netWorkProxy = null // 用于存储 Proxy 拦截器
    tryCount = 0
    networkStatus = {
      isConnected: true, // 是否联网
      networkType: "wifi", // 网络类型
      weakNet: false,   // 弱网状态
      signalStrength: false,   // 信号强度
      ip: "",
    }

    constructor(parameters) {
      this.pageContext = parameters;
      this.create()
    }
    create() {
      this.onNetworkStatusChange()
    }
    // 获取初始网络状态
    createGetNetworkType(){
      const _this = this
      wx.getNetworkType({
        success(res) {
          _this.tryCount = 0
          // ip
          wx.getLocalIPAddress({
          complete (res) {
              _this.networkStatus.ip = res.localip
              _this.networkStatus.networkType = res.networkType || "unknown"
              _this.networkStatus.isConnected = res.networkType !== 'none'
              _this.networkStatus.weakNet = res.weakNet
              _this.networkStatus.signalStrength = res.signalStrength
              // 如果有页面注册了回调，则执行
              if (_this.netWorkProxy) {
                _this.netWorkProxy.triggerNetworkChange();
              }
            }
          })
        },
        fail(){
          if(_this.tryCount === 3){
            _this.tryCount = 0
            return;
          }
          _this.tryCount++
          _this.createGetNetworkType()
        }
      });
    }
    // 网络状态变化事件的监听函数
    onNetworkStatusChange(){
      const _this = this
      _this.networkStatusChange = wx.onNetworkStatusChange(function (res) {
          _this.createGetNetworkType()
      })
    }

    // 提供给页面的网络拦截器
    netWorkCallback(callback) {
      const _this = this;
      const handler = {
        // 拦截网络变化
        triggerNetworkChange() {
          if (typeof callback === "function") {
            callback(_this.networkStatus);
          }
        },
      };
      // 存储 Proxy 对象（可选）
      this.netWorkProxy = new Proxy(handler, {});
      this.createGetNetworkType()
    }
    // 销毁
    destroy() {
      if(this.networkStatusChange) wx.onNetworkStatusChange(this.networkStatusChange)
      this.netWorkProxy = null
    }
}
